const adminDao = require("../dao/adminDao");
const md5 = require("md5");
const JWT = require("jsonwebtoken");
const { ValidationError } = require("../utils/errors");

exports.login = async (loginInfo) => {
    loginInfo.loginPwd = md5(loginInfo.loginPwd);
    const result = await adminDao.login(loginInfo);

    if (result) {
        // 添加token
        delete result.loginPwd;
        const loginPeriod = (loginInfo.remember ? 7 : 1) * 3600 * 24 * 1000;
        const token = JWT.sign(result, md5(process.env.JWT_SECRET), {
            algorithm: "HS256",
            expiresIn: loginPeriod
        });
        return {
            data: result,
            token
        }
    }

    return {
        data: result
    }
}

exports.updateAdmin = async (accountInfo) => {
    const res = await adminDao.login({
        loginId: accountInfo.loginId,
        loginPwd: md5(accountInfo.oldLoginPwd)
    });
    if (res) {
        console.log("success");
        accountInfo = {
            name: accountInfo.name,
            loginId: accountInfo.loginId,
            loginPwd: md5(accountInfo.newLoginPwd)
        }
        await adminDao.updateAdmin(accountInfo);
        return {
            id: res.id,
            name: accountInfo.name,
            loginId: accountInfo.loginId
        }
    } else {
        throw new ValidationError("旧密码不正确");
    }
}
